﻿using MetroDataApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MetroDataApi.Controllers.Management
{
    public class monitorTypesController : ApiController
    {
        // GET api/monitortypes
        public string Get()
        {
            using (var db = new MetroDataDataContext())
            {
                var list = (from t in db.MonitorTypes select t.MonitorType).ToList();
                return JsonConvert.SerializeObject(list);
            }
        }

        // GET api/monitortypes/5
        public string Get(int prjId)
        {
            using (var db = new MetroDataDataContext())
            {
                var list = (from t in db.PrjMonitorTypes where t.PrjId==prjId select t.MonitorType).ToList();
                return JsonConvert.SerializeObject(list);
            }
        }

        // POST api/monitortypes
        public bool Post([FromBody]string value)
        {
            //pras:monitorTypes, autoSurveyList
            JObject jsonData = JObject.Parse(value);
            var prjId = jsonData["prjId"].ToObject<int>();
            var monitorTypes = jsonData["monitorTypes"].ToObject<string[]>();
            var autoSurveyList = jsonData["autoSurveyList"].ToObject<List<stations>>();
            using (var db = new MetroDataDataContext())
            {
                var oldTypesList = db.PrjMonitorTypes.Where(p => p.PrjId == prjId).ToList();
                db.PrjMonitorTypes.DeleteAllOnSubmit(oldTypesList);
                var newTypesList = 
                    monitorTypes.ToList().Select(
                        p => new PrjMonitorTypes { MonitorType = p, PrjId = prjId, Remark = null });
                db.PrjMonitorTypes.InsertAllOnSubmit(newTypesList);
                db.SubmitChanges();
            }
            if (monitorTypes.ToList().IndexOf("自动化收敛") > -1)
            {
                using (var dbauto = new AutoSurveyDataDataContext())
                {
                    foreach (var st in autoSurveyList)
                    {
                        var station = dbauto.stations.SingleOrDefault(s => s.stationid == st.stationid);
                        station.prjid = st.prjid;
                        dbauto.SubmitChanges();
                    }

                }
            }

            return true;

        }

        // PUT api/monitortypes/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/monitortypes/5
        public void Delete(int id)
        {
        }
    }
}
